import { useContext, useEffect, useState } from 'react';

import { CreateReview, Review } from '@/entities/rating';
import { ModalContext } from '@/shared/context/ModalContext';
import { Modals } from '@/shared/interfaces';
import { RatingDto } from '@/shared/interfaces/generated';
import { Button, Title } from '@/shared/ui';
import { ModalPage } from '@/widgets/ModalPage';
import cn from 'classnames';
import { useRouter } from 'next/router';
import { useWindowSize } from 'usehooks-ts';

import cs from './ReviewList.module.scss';

export const ReviewList = <T,>({
  id,
  ratings,
  canCreate,
  onCreate,
  ratingId,
}: {
  ratingId?: number;
  ratings: RatingDto[];
  id?: string;
  canCreate?: boolean;
  onCreate: (...args: any) => Promise<T>;
}) => {
  const [star, setStar] = useState(0);
  const [textValue, setTextValue] = useState('');
  const router = useRouter();
  const { width } = useWindowSize();
  const [isOpen, setIsOpen] = useState(false);
  const { openModal, closeModal, setData, data } = useContext(ModalContext);
  const [isShowAll, setIsShowAll] = useState(false);
  const handleClearAreas = () => {
    setTextValue('');
    setStar(0);
  };
  const handleModalPageClose = () => {
    if (width >= 768 || !textValue.length || !star) {
      setIsOpen(false);
      return;
    }
    openModal(Modals.SendReview);
    const { id } = router.query;
    const data: { id: number; rate: number; comment?: string } = {
      id: Number(id),
      rate: star,
      comment: textValue.trim(),
    };
    setData(() => ({ ...data }));
  };
  const handleModalPageOpen = () => {
    setIsOpen(true);
    handleClearAreas();
    setTimeout(() => setData(() => ({})));
  };

  useEffect(() => {
    if (isOpen && data.check === 'exit') {
      handleClearAreas();
      setIsOpen(false);
      closeModal();
    }
  }, [data]);

  return (
    <>
      <div className={cs.block}>
        <div className={cs.header}>
          <Title size="l" tag="h3">
            Отзывы <span className={cs.sub}>{ratings?.length || ''}</span>
          </Title>
          {ratings?.length > 4 && (
            <div className={cn(cs.blue_text, cs.mobile)} onClick={handleModalPageOpen}>
              Все
            </div>
          )}
        </div>
        {canCreate && !ratingId && (
          <CreateReview
            createReview={onCreate}
            id={id}
            setStar={setStar}
            setTextValue={setTextValue}
            star={star}
            textValue={textValue}
            withPrevent
          />
        )}
        {!!ratings.length && (
          <>
            <div className={cs.review_list}>
              {(isShowAll ? ratings : ratings.slice(0, 4))?.map((review) => (
                <Review key={review.id} {...review} />
              ))}
              {ratings.length > 4 && (
                <Button
                  className={cn(cs.blue_text, cs.desktop)}
                  data-testid="button-show_all"
                  onClick={() => setIsShowAll(true)}
                >
                  {!isShowAll && 'Показать все'}
                </Button>
              )}
            </div>
          </>
        )}
        {!ratings?.length && (!canCreate || ratingId) && <p className={cs.no_reviews}>Отзывов пока нет</p>}
      </div>
      <ModalPage handleClose={() => handleModalPageClose()} isMobile isOpen={isOpen}>
        <div>
          <div className={cs.header}>
            <div className={cn(cs.title, cs.modal_title)}>
              Отзывы <span className={cs.modal_sub}>{ratings?.length || ''}</span>
            </div>
          </div>
          <div>
            {canCreate && !ratingId && (
              <CreateReview
                createReview={onCreate}
                id={id}
                setStar={setStar}
                setTextValue={setTextValue}
                star={star}
                textValue={textValue}
                withPrevent
              />
            )}
            <div className={cs.review_list}>
              {ratings?.map((review) => (
                <Review key={review.id} {...review} />
              ))}
            </div>
          </div>
        </div>
      </ModalPage>
    </>
  );
};
